package com.stock.util;

import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.stock.service.StockService;

public class EmailNotify {
	private static final Logger log = LogManager.getLogger(StockService.class);
	 
	private static Session session; 
	
	public static Session getSession() {
		
		if (session ==null) {
			Properties props = new Properties();
			props.put("mail.smtp.auth", "true");
			props.put("mail.smtp.starttls.enable", "true");
			props.put("mail.smtp.host", "smtp.gmail.com");
			props.put("mail.smtp.port", "587");
		    session = Session.getInstance(props, new Authenticator() {
				   protected PasswordAuthentication getPasswordAuthentication() {
					   return new PasswordAuthentication(Property.EMAIL_ACCOUNT, Property.EMAIL_PASSWORD);
				   }
			});
		} 
		
		return session; 
	}
	
	public static void send(String toEmail, String subject, String text){
	   try {
		   Message message = new MimeMessage(getSession());
		   message.setFrom(new InternetAddress(Property.EMAIL_FROM));
		   message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(Property.EMAIL_TO));
		   message.setSubject(subject);
		   message.setText(text);
		   Transport.send(message);
	   } catch (MessagingException e) {
			e.printStackTrace();
			log.error(e);
		}
	  
	}
}